package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import com.example.demo.service.handler.IWxMessageFactory;
import com.example.demo.service.handler.IWxMessageHandler;
import com.example.demo.util.XMLUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Map;


@Controller
@RequestMapping("/api/wx")
public class WxApiController {
    private Logger logger = LoggerFactory.getLogger(WxApiController.class);
    @Resource
    private UserService userService;
    @Autowired
    private IWxMessageFactory iWxMessageFactory;

    /**
     * 接入时使用
     */
    @ResponseBody
    @GetMapping
    public String verifyUrl(String signature, String timestamp, String nonce, String echostr) {
        String token = "123456";
        logger.info("signature:" + signature);
        logger.info("timestamp:" + timestamp);
        logger.info("nonce:" + nonce);
        logger.info("token:" + token);
        logger.info("echostr:" + echostr);
        String strs[] = {timestamp, nonce, token};
        Arrays.sort(strs);
        String singe = StringUtils.join(strs);
        String res = DigestUtils.sha1Hex(singe);
        logger.info("sha1Hex:" + res);
        if (res.equals(signature)) {
            return echostr;
        }
        return "echostr";
    }

    @ResponseBody
    @RequestMapping("/test")
    public String test() {
        User user = new User();
        user.setAddress("123");
        user.setName("hello world");
        user.setId_no("123");
        long id = userService.saveUser(user);
        return String.valueOf(id);

    }

    /**
     * 接收消息
     */
    @ResponseBody
    @PostMapping
    public String recevieMessage(HttpServletRequest request, String signature, String timestamp, String nonce) throws IOException {
        logger.info("signature:" + signature);
        logger.info("timestamp:" + timestamp);
        logger.info("nonce:" + nonce);
        InputStream is = request.getInputStream();
        try {
            Map<String, String> message = XMLUtil.parseXml(is);
            message.forEach((m, n) -> {
                logger.info(m);
                logger.info(n);
            });
            String MsgType = message.get("MsgType");
            IWxMessageHandler iWxMessageHandler = iWxMessageFactory.createMessage(MsgType);
            String result = iWxMessageHandler.handlerMessage(message);
            logger.info(result);
            return result;
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            is.close();
        }
        return "success";
    }


}
